package service

import (
	"dataaysn/internal/model"
	"dataaysn/internal/repository"
	"strconv"

	"github.com/gin-gonic/gin"
)

type SSHConfigService struct {
	repo repository.SSHConfigRepository
}

func NewSSHConfigService(repo repository.SSHConfigRepository) *SSHConfigService {
	return &SSHConfigService{repo: repo}
}

func (s *SSHConfigService) CreateConfig(c *gin.Context) {
	var config model.SSHConfig
	if err := c.ShouldBindJSON(&config); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.CreateConfig(&config); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, config)
}

func (s *SSHConfigService) GetConfig(c *gin.Context) {
	id := c.Param("id")
	config, err := s.repo.GetConfig(id)
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, config)
}

func (s *SSHConfigService) UpdateConfig(c *gin.Context) {
	id := c.Param("id")
	var config model.SSHConfig
	if err := c.ShouldBindJSON(&config); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	uintID, err := strconv.ParseUint(id, 10, 32)
	if err != nil {
		c.JSON(400, gin.H{"error": "invalid id format"})
		return
	}
	config.ID = uint(uintID)
	if err := s.repo.UpdateConfig(&config); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, config)
}

func (s *SSHConfigService) DeleteConfig(c *gin.Context) {
	id := c.Param("id")
	if err := s.repo.DeleteConfig(id); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"message": "deleted"})
}

func (s *SSHConfigService) ListConfigs(c *gin.Context) {
	configs, err := s.repo.ListConfigs()
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, configs)
}

func (s *SSHConfigService) TestConnection(c *gin.Context) {
	var config model.SSHConfig
	if err := c.ShouldBindJSON(&config); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.TestConnection(&config); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, gin.H{"message": "connection successful"})
}
